package com.wxs.config;

import com.wxs.pojo.User;
import com.wxs.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {


    @Autowired
    UserService userService;

    /*Authorization 授权*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了Authorization 授权");
        return null;
    }

    /*Authentication 认证 证明*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行类Authentication 认证");

        /*用户名 密码 --》 数据库中取*/
        /*String username= "root";
        String password ="root123";*/

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        /*  if (!userToken.getUsername().equals(name)) {
           return null;   //UnknownAccountException
        }*/
        System.out.println(userToken.getUsername());
        System.out.println(userToken.getPassword());
        System.out.println(userToken.getCredentials());
        System.out.println(getName());

        User user = userService.queryUserByName(userToken.getUsername());
        System.out.println(user);
        if (user == null){
            return null; /*抛出异常*/
        }


        /*密码认证*/
       /* return new SimpleAuthenticationInfo("",password,"");*/
        /*return  new SimpleAuthenticationInfo(user,user.getPwd(),"");*/
        //3.通过SimpleAuthenticationInfo做身份处理
        return new SimpleAuthenticationInfo(user,
                user.getPwd(),
                ByteSource.Util.bytes(user.getSalt()),
                getName());



    }
}
